<template>
  <div class="page-container">
    <!-- 顶部标题栏 -->
    <header class="header">
      <BackBtn />
      <h1>主页编辑</h1>
      <Time />
    </header>

    <div class="main-content">
      <div class="section-container">
        <h2 class="section-title">主页轮播图</h2>
        <CarouselUpload />
      </div>
    </div>

    <!-- 滚动通知 -->
    <div class="notification-section">
      <h2 class="section-title">滚动通知</h2>
      <div class="notification-list" v-loading="pageLoading" element-loading-text="加载中..."
        :element-loading-background="'rgba(0, 0, 0, 0)'"
      >
        <div class="list">
          <!-- 通知列表 -->
          <div v-for="(item) in notifications" :key="item.nid" class="admin-item">
            <div class="notification-content">
              <el-input v-model="item.content" type="textarea" :rows="2" class="notification-input" maxlength="20"
                show-word-limit @change="handleNotificationChange(item)" />
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- 保存按钮 -->
    <div class="save-actions">
      <el-button type="danger" @click="handleSaveNotifications" :loading="isSaving" class="save-button">确认保存</el-button>
    </div>

  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import CarouselUpload from '@/components/CarouselUpload.vue'
import { ElMessage } from 'element-plus'
import { getNotificationsList, updateNotification } from '@/api/topic'
import Time from '@/components/Time.vue'
import BackBtn from '@/components/Back-btn.vue'

const notifications = ref([])
const isSaving = ref(false)
const modifiedNotifications = ref(new Set())
const pageLoading = ref(false)

// 获取通知列表
const fetchNotifications = async () => {
  try {
    const res = await getNotificationsList()
    if (res.code === 200) {
      notifications.value = res.data
    }
  } catch (error) {
    ElMessage.error('获取通知列表失败')
  }
}

// 处理通知内容变化
const handleNotificationChange = (notification) => {
  modifiedNotifications.value.add(notification.nid)
}

// 保存修改的通知
const handleSaveNotifications = async () => {
  if (modifiedNotifications.value.size === 0) {
    ElMessage.info('没有需要保存的修改')
    return
  }

  isSaving.value = true
  try {
    const updatedNotifications = notifications.value.filter(item =>
      modifiedNotifications.value.has(item.nid)
    )

    for (const notification of updatedNotifications) {
      const res = await updateNotification(notification)
      if (res.code !== 200) {
        throw new Error(res.msg || '保存失败')
      }
    }

    ElMessage.success('保存成功')
    modifiedNotifications.value.clear()
  } catch (error) {
    ElMessage.error(error.message || '保存失败')
  } finally {
    isSaving.value = false
  }
}

onMounted(async () => {
  pageLoading.value = true
  try {
    await fetchNotifications()
  } finally {
    pageLoading.value = false
  }
})
</script>


<style scoped>
@import '@/assets/css/topic/topic.css';
@import '@/assets/css/header/index.css';
</style>